<template>
  <view class="container">
    <!-- Tab栏 -->
    <view class="bottom-tab">
      <view :class="classNameArr[0]" @click="changeTab(0)">进行中</view>
      <view :class="classNameArr[1]" @click="changeTab(1)">已过期</view>
    </view>

    <!-- 纪念日列表 -->
    <view class="task-list">
      <!-- 使用 uni-swipe-action 包裹每个 task-item -->
      <uni-swipe-action v-for="day in days" :key="day.id">
        <uni-swipe-action-item>
          <!-- 左滑时显示的操作按钮 -->
          <template v-slot:right>
            <view class="swipe-buttons">
              <button @click="handleEdit(day)" class="edit-btn">编辑</button>
              <button @click="handleDelete(day.id)" class="delete-btn">删除</button>
            </view>
          </template>
          <!-- 正常的 task-item 内容 -->
          <view class="task-item">
            <view class="task-time">
              {{ day.targetTime }}
            </view>
            <text class="task-title">{{ day.title }}</text>
            <view class="task-count-next">
              <text v-if="day.nextDays >= 0">下次还剩: {{ day.nextDays }} 天</text>
              <text v-else>已过期</text>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>

    <!-- 浮动按钮 -->
    <view class="floating-button" :style="{ left: `${position.left}px`, top: `${position.top}px` }"
      @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @click="openDayPopup">
      <view class="plus-icon">+</view>
    </view>
    <!-- 添加纪念日的弹窗 -->
    <uni-popup ref="dayPopup" :show="showPopup" @close="showPopup = false">
      <view class="popup-content">
        <view class="form">
          <input v-model="newDay.title" placeholder="纪念日标题" class="task-input" />
          <uni-datetime-picker v-model="newDay.targetTime" type="date" />
          <view class="button-group">
            <button @click="addDay" class="add-button">添加纪念日</button>
            <button @click="closeTaskPopup" class="cancel-button">取消</button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import UniPopup from '../../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
import UniSwipeAction from '../../../uni_modules/uni-swipe-action/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '../../../uni_modules/uni-swipe-action/components/uni-swipe-action-item/uni-swipe-action-item.vue'
import { CountDownDayAdd, CountDownDayDel, CountDownDayListByStatus, CountDownDayUpdate } from '@/api/countDownDay/countDownDay';

interface Day {
  id?: number;
  title?: string;
  targetTime?: string; // 公历日期
  nextDays?: number; // 下次天数
}
// Tab栏状态
const tabNumNow = ref(0); // 当前选中的Tab索引
const tabs = ['公历', '农历']; // Tab栏的标题
const classNameArr = ref<string[]>([]); // Tab栏的类名数组
const initTabs = () => {
  classNameArr.value = tabs.map((_, index) =>
    index === tabNumNow.value ? 'tab-item-active' : 'tab-item-default'
  );
};
initTabs(); // 初始化
const changeTab = (tabNum: number) => {
  tabNumNow.value = tabNum;
  classNameArr.value = tabs.map((_, index) =>
    index === tabNumNow.value ? 'tab-item-active' : 'tab-item-default'
  );
  init();
};

// 纪念日列表
const days = ref<Day[]>(null);
const init = async () => {
  const res = await CountDownDayListByStatus(tabNumNow.value);
  days.value = res.data
}
onMounted(() => {
  init();
})

// 表单弹窗相关
const showPopup = ref(false);
const dayPopup = ref(null);
const openDayPopup = () => {
  if (dayPopup.value) {
    showPopup.value = true;
    dayPopup.value.open("dayPopup");
  }
};

interface NewTask {
  title: string;
  targetTime: string;
}

// 纪念日表单数据
const newDay = ref<NewTask>({
  title: '',
  targetTime: '',
});

const closeTaskPopup = () => {
  if (dayPopup.value) {
    showPopup.value = false;
    dayPopup.value.close();
    newDay.value = { title: '', targetTime: '' }; // 重置表单
    currentDayId.value = null;
  }
}

// 添加日
const addDay = async () => {
  if (newDay.value.title.trim() === '') {
    uni.showToast({
      title: '标题不能为空',
      icon: 'none',
    });
    return;
  }
  const day2: Day = {
      title: newDay.value.title,
      targetTime: newDay.value.targetTime
    }
  if (currentDayId.value != null || currentDayId.value != undefined) {
    // 修改
    day2.id = currentDayId.value;
    await CountDownDayUpdate(day2);
  } else {
    // 保存
    await CountDownDayAdd(day2);
  }

  init();
  closeTaskPopup();
};

// 可移动按钮
const position = ref({ left: uni.getSystemInfoSync().screenWidth - 70, top: uni.getSystemInfoSync().screenHeight - 140 });
const startTouch = ref({ x: 0, y: 0 });
const isDragging = ref(false);
const onTouchStart = (event: TouchEvent) => {
  const touch = event.touches[0];
  startTouch.value = {
    x: touch.clientX - position.value.left,
    y: touch.clientY - position.value.top,
  };
  isDragging.value = true;
};

const onTouchMove = (event: TouchEvent) => {
  if (!isDragging.value) return;
  const touch = event.touches[0];
  const newLeft = touch.clientX - startTouch.value.x;
  const newTop = touch.clientY - startTouch.value.y;
  const systemInfo = uni.getSystemInfoSync();
  const maxLeft = systemInfo.screenWidth - 50;
  const maxTop = systemInfo.screenHeight - 100;
  position.value.left = Math.max(0, Math.min(newLeft, maxLeft));
  position.value.top = Math.max(0, Math.min(newTop, maxTop));
};
const onTouchEnd = () => {
  isDragging.value = false;
};

// 列表元素左滑
// 处理编辑按钮点击事件
const currentDayId = ref(null);
const handleEdit = (day: Day) => {
  console.log('编辑任务:', day);
  newDay.value.title = day.title;
  newDay.value.targetTime = day.targetTime;
  currentDayId.value = day.id;
  openDayPopup();
};

// 处理删除按钮点击事件
const handleDelete = async (taskId: number) => {
  console.log('删除任务:', taskId);
  await CountDownDayDel(taskId);
  init();
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  text-align: center;
  height: 98vh;
  padding: 1vh 20px;
  overflow-y: hidden;
  overflow-x: hidden;
  background-color: #fff;
}

.bottom-tab {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0);
  padding: 10px 0;
  height: 30px;
  width: 90vw;
  border-top: 1px solid #eee;
  text-align: center;
}

.tab-item-default {
  font-size: 14px;
  color: #4c88ad;
  height: 100%;
  width: 25%;
  opacity: 0.5;
}

.tab-item-active {
  font-size: 14px;
  height: 100%;
  width: 25%;
  color: #4c88ad;
}

.task-list {
  margin-top: 10px;
  padding: 10px;
  width: 96%;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow-y: scroll;
  overflow-x: hidden;
}

.task-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  height: 40px;
  border-bottom: 1px solid #eee;
  border-radius: 10px;
  border: 1px solid #ddd;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.task-time {
  position: absolute;
  left: 10px;
  bottom: 10px;
  font-size: 10px;
  color: rgba(82, 74, 74, 0.5);
}

.task-title {
  position: absolute;
  left: 10px;
  top: 10px;
  font-size: 14px;
  margin-top: 8px;
  flex-grow: 1;
}

/* 距离第一次的样式，固定在右下角，带有渐变文字效果 */
.task-count-first {
  position: absolute;
  /* 使用绝对定位 */
  bottom: 10px;
  /* 固定在父容器底部10px处 */
  right: 10px;
  /* 固定在父容器右侧10px处 */
  font-size: 16px;
  font-weight: 600;
  color: transparent;
  -webkit-background-clip: text;
  background-clip: text;
  background-image: linear-gradient(45deg, #ff7e5f, #feb47b);
  font-family: 'Arial', sans-serif;
  letter-spacing: 0.5px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  /* 为了适配不同屏幕，可以考虑使用媒体查询来调整bottom和right的值 */
}

/* 距离下一次的样式，同样固定在右下角，带有渐变文字效果 */
.task-count-next {
  position: absolute;
  /* 使用绝对定位 */
  bottom: 30px;
  /* 固定在父容器底部10px处 */
  right: 10px;
  /* 固定在父容器右侧10px处 */
  font-size: 16px;
  font-weight: 600;
  color: transparent;
  -webkit-background-clip: text;
  background-clip: text;
  background-image: linear-gradient(45deg, #8e44ad, #4a90e2);
  font-family: 'Arial', sans-serif;
  letter-spacing: 0.5px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  /* 同样，为了适配不同屏幕，可以考虑使用媒体查询 */
}


.floating-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background-color: #007AFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  cursor: pointer;
}

.popup-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  width: 300px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.add-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
}

.add-button:hover,
.cancel-button:hover {
  opacity: 0.9;
}

.floating-button {
  position: fixed;
  right: 10px;
  bottom: 10px;
  width: 50px;
  height: 50px;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 9999;
}

.plus-icon {
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.swipe-buttons {
  display: flex;
  align-items: center;
  height: 100%;
}

.edit-btn,
.delete-btn {
  /* margin: 10px; */
  border-radius: 0;
  /* 完成按钮背景色 */
  color: white;
  border-radius: 10px;
}

.edit-btn {
  background-color: #FFC107;
  /* 编辑按钮背景色 */
}

.delete-btn {
  background-color: #F44336;
  /* 删除按钮背景色 */
}
</style>